package com.aco.fatureapp.fragments;

import java.util.List;

import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;

import com.aco.fatureapp.R;
import com.aco.fatureapp.enums.EnumRelatorioLeitura;
import com.aco.fatureapp.model.Roteiro;
import com.aco.fatureapp.model.printer.PrinterResumo;
import com.aco.fatureapp.printer.libs.Printer2;
import com.aco.fatureapp.service.SrvMetering;
import com.aco.fatureapp.utilitary.CallAsyncTask;
import com.aco.fatureapp.utilitary.DataUtils;
import com.aco.fatureapp.utilitary.Utils;
import com.google.inject.Inject;

public class RelLeiturasFragment extends Fragment {

	private EditText mTxtPosicaoInicial;

	private EditText mTxtPosicaoFinal;

	private Spinner mSpnTipoRelatorio;

	private LinearLayout mPnlPosicao;

	/*
	 * Serviço
	 */
	@Inject
	private SrvMetering mSrvMetering;

	Printer2 mPrinter = new Printer2();

	/*
	 * (non-Javadoc)
	 *
	 * @see android.app.Fragment#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);

		if (mSrvMetering == null) {
			mSrvMetering = new SrvMetering();
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.app.DialogFragment#onCreateDialog(android.os.Bundle)
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.fragment_rel_leituras,
				container, false);

		mTxtPosicaoInicial = (EditText) rootView
				.findViewById(R.id.txtPosicaoInicial);
		mTxtPosicaoFinal = (EditText) rootView
				.findViewById(R.id.txtPosicaoFinal);
		mSpnTipoRelatorio = (Spinner) rootView
				.findViewById(R.id.spnTipoRelatorio);

		mPnlPosicao = (LinearLayout) rootView.findViewById(R.id.pnlPosicao);

		popularSpinner();

		return rootView;

	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.app.Fragment#onCreateOptionsMenu(android.view.Menu,
	 * android.view.MenuInflater)
	 */
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.action_bar_menu_rel_leituras, menu);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see android.app.Fragment#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.action_print: {

			final String macPrinter = mSrvMetering.getMacImpressora();

			if (macPrinter == null) {
				Utils.alert(getActivity(),
						"Impressora padrão não está configurada!", null);
				return false;
			}

			CallAsyncTask callAsyncTask = new CallAsyncTask(getActivity(), true);

			callAsyncTask.execute(new CallAsyncTask.Action() {

				@Override
				public String execute() {

					try {
						String selectedItem = (String) mSpnTipoRelatorio
								.getSelectedItem();

						if (selectedItem != null) {
							EnumRelatorioLeitura enumRelatorioLeitura = EnumRelatorioLeitura
									.valueOfDesc(selectedItem);

							List<PrinterResumo> lstPrinterResumo = null;

							if (enumRelatorioLeitura != null) {

								String erro = null;

								switch (enumRelatorioLeitura) {
								case NAO_EMITIDA: {
									lstPrinterResumo = mSrvMetering
											.getLstPrinterResumo();
									break;
								}
								case PARCIAL: {
									String pos1 = mTxtPosicaoInicial.getText()
											.toString();

									String pos2 = mTxtPosicaoFinal.getText()
											.toString();

									if (pos1 == null || pos1.length() == 0
											|| pos2 == null
											|| pos2.length() == 0) {
										erro = "Informe a posição inicial e final para imprimir o relatório";
										break;
									}

									Integer posicaoInicial = Integer
											.valueOf(pos1);

									Integer posicaoFinal = Integer
											.valueOf(pos2);

									lstPrinterResumo = mSrvMetering
											.getLstPrinterResumoParcial(
													posicaoInicial,
													posicaoFinal);
									break;
								}
								case TODAS: {
									lstPrinterResumo = mSrvMetering
											.getLstPrinterResumoTodas();
									break;
								}
								}

								if (erro != null) {
									return erro;
								}

								if (lstPrinterResumo == null
										|| lstPrinterResumo.isEmpty()) {
									return "Não foram encontrados registros para impressão do resumo";
								}

								Roteiro roteiro = mSrvMetering.getRoteiro();

								Long idCarga = mSrvMetering.getIdCarga();

								if (roteiro == null || idCarga == null) {
									return "Não existe carga no momento.";
								}

								if (mPrinter
										.checkBth(getActivity(), macPrinter)) {
									// Imprimir resumo.
									Printer2.imprimirResumo(
											roteiro.getNumero(),
											idCarga,
											Utils.getImei(getActivity()),
											DataUtils
													.formatarCompetencia(roteiro
															.getCompetencia()),
											lstPrinterResumo,
											mPrinter.mBth.ostream);
								}

								if (EnumRelatorioLeitura.NAO_EMITIDA
										.equals(enumRelatorioLeitura)) {
									mSrvMetering
											.markBillPrinting(lstPrinterResumo);
								}
							}
						}

						return null;
					}
					catch (Exception ex) {

						Log.e("Impressao_conta", ex.getLocalizedMessage());
						return ex.getLocalizedMessage();
					}
				}
			});
		}
		}

		return super.onOptionsItemSelected(item);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void popularSpinner() {
		final List<String> niveis = EnumRelatorioLeitura.getLstDescricao();

		final ArrayAdapter adapter = new ArrayAdapter(getActivity(),
				R.layout.adapter_spinner, niveis);

		adapter.setDropDownViewResource(R.layout.adapter_spinner);

		mSpnTipoRelatorio.setAdapter(adapter);

		/**
		 * Evento do spinner.
		 */
		mSpnTipoRelatorio
				.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
					@Override
					public void onItemSelected(final AdapterView<?> arg0,
							final View arg1, final int index, final long arg3) {
						if (index == 1) {
							mPnlPosicao.setVisibility(View.VISIBLE);
						}
						else {
							mPnlPosicao.setVisibility(View.GONE);
							mTxtPosicaoInicial.setText(null);
							mTxtPosicaoFinal.setText(null);
						}
					}

					@Override
					public void onNothingSelected(final AdapterView<?> arg0) {
					}
				});
	}
}